package com.flowable.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.common.api.BusinessApi;
import com.common.core.domain.AjaxResult;
import com.common.core.domain.entity.ProcessConfig;
import com.common.core.domain.entity.SysUser;
import com.common.core.service.ProcessConfigService;
import com.common.utils.SecurityUtils;
import com.common.utils.StringUtils;
import com.common.utils.bean.BeanUtils;
import com.flowable.candidate.BpmTaskCandidateInvoker;
import com.flowable.common.*;
import com.flowable.common.enums.*;
import com.flowable.common.enums.definition.BpmUserTaskAssignEmptyHandlerTypeEnum;
import com.flowable.common.enums.task.BpmReasonEnum;
import com.flowable.controller.oa.vo.DeptRespDTO;
import com.flowable.convert.task.BpmProcessInstanceConvert;
import com.flowable.domain.dto.BpmProcessInstanceCreateReqDTO;
import com.flowable.domain.instance.*;
import com.flowable.domain.vo.BpmTaskRespVO;
import com.flowable.domain.vo.FlowTaskVo;
import com.flowable.common.enums.definition.BpmSimpleModelNodeType;
import com.flowable.event.BpmProcessInstanceEventPublisher;
import com.flowable.factory.FlowServiceFactory;
import com.flowable.mapper.FlowDeployMapper;
import com.flowable.service.IFlowInstanceService;
import com.flowable.service.IFlowTaskService;
import com.flowable.service.message.BpmMessageService;
import com.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.constants.BpmnXMLConstants;
import org.flowable.bpmn.model.*;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.engine.delegate.event.FlowableProcessStartedEvent;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.TaskQuery;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

import static com.common.exception.ServiceExceptionUtil.exception;
import static com.common.utils.CollectionUtils.*;
import static com.flowable.common.enums.BpmnModelConstants.START_USER_NODE_ID;
import static com.flowable.common.enums.ErrorCodeConstants.*;
import static com.flowable.common.enums.ErrorCodeConstants.PROCESS_DEFINITION_IS_SUSPENDED;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.flowable.bpmn.constants.BpmnXMLConstants.*;

/**
 * <p>工作流流程实例管理<p>
 *
 * @author Tony
 * @date 2021-04-03
 */
@Service
@Slf4j
public class FlowInstanceServiceImpl extends FlowServiceFactory implements IFlowInstanceService {

    @Resource
    @Lazy // 避免循环依赖
    private IFlowTaskService flowTaskService;

    @Autowired
    private ISysUserService userService;



    @Resource
    private BpmTaskCandidateInvoker taskCandidateInvoker;


    @Resource
    private Map<String, BusinessApi> businessApi;

    @Resource
    private FlowDeployMapper flowDeployMapper;


    @Autowired
    ProcessConfigService processConfigService;

    @Resource
    private BpmMessageService messageService;

//    @Resource
//    private BpmProcessInstanceEventPublisher processInstanceEventPublisher;


    /**
     * 结束流程实例
     *
     * @param vo
     */
    @Override
    public void stopProcessInstance(FlowTaskVo vo) {
        String taskId = vo.getTaskId();

    }

    /**
     * 激活或挂起流程实例
     *
     * @param state      状态
     * @param instanceId 流程实例ID
     */
    @Override
    public void updateState(Integer state, String instanceId) {

        // 激活
        if (state == 1) {
            runtimeService.activateProcessInstanceById(instanceId);
        }
        // 挂起
        if (state == 2) {
            runtimeService.suspendProcessInstanceById(instanceId);
        }
    }

    /**
     * 删除流程实例ID
     *
     * @param instanceId   流程实例ID
     * @param deleteReason 删除原因
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String instanceId, String deleteReason) {

        // 查询历史数据
        HistoricProcessInstance historicProcessInstance = getHistoricProcessInstanceById(instanceId);
        if (historicProcessInstance.getEndTime() != null) {
            historyService.deleteHistoricProcessInstance(historicProcessInstance.getId());
            return;
        }
        // 删除流程实例
        runtimeService.deleteProcessInstance(instanceId, deleteReason);
        // 删除历史流程实例
        historyService.deleteHistoricProcessInstance(instanceId);
    }

    @Override
    public void deletebyKey(String processkey) {
        HistoricProcessInstanceQuery processInstanceQuery = historyService.createHistoricProcessInstanceQuery()
                .includeProcessVariables()
                .processDefinitionKey(processkey)
                .orderByProcessInstanceStartTime().desc();
        List<HistoricProcessInstance> processInstanceList= processInstanceQuery.list();

        if (!CollUtil.isEmpty(processInstanceList)) {
            String[] instanceIds = processInstanceList.stream()
                    .map(instance -> (String) instance.getId()) // 强制转换很重要，确保类型安全
                    .toArray(String[]::new);
            for (String instanceId : instanceIds) {
                delete(instanceId,"");
            }
        }

    }

    /**
     * 根据实例ID查询历史实例数据
     *
     * @param processInstanceId
     * @return
     */
    @Override
    public HistoricProcessInstance getHistoricProcessInstanceById(String processInstanceId) {
        HistoricProcessInstance historicProcessInstance =
                historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if (Objects.isNull(historicProcessInstance)) {
            throw new FlowableObjectNotFoundException("流程实例不存在: " + processInstanceId);
        }
        return historicProcessInstance;
    }


    //芋道发起流程实例
    public String createProcessInstance(Long userId, BpmProcessInstanceCreateReqDTO createReqDTO) {
        // 获得流程定义
        ProcessDefinition definition = getActiveProcessDefinition(createReqDTO.getProcessDefinitionKey());
        // 发起流程
        return createProcessInstance0(userId, definition, createReqDTO.getVariables(), createReqDTO.getBusinessKey(),
                createReqDTO.getStartUserSelectAssignees(),createReqDTO.getTableName());

    }

    public ProcessDefinition getActiveProcessDefinition(String key) {
        return repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(key).active().singleResult();
    }
    private String createProcessInstance0(Long userId,ProcessDefinition definition,
                                          Map<String, Object> variables, String businessKey,
                                          Map<String, List<Long>> startUserSelectAssignees,String tableName) {
        // 1.1 校验流程定义
        if (definition == null) {
            throw exception(PROCESS_DEFINITION_NOT_EXISTS);
        }
        if (definition.isSuspended()) {
            throw exception(PROCESS_DEFINITION_IS_SUSPENDED);
        }
//        BpmProcessDefinitionInfoDO processDefinitionInfo = processDefinitionService.getProcessDefinitionInfo(definition.getId());
//        if (processDefinitionInfo == null) {
//            throw exception(PROCESS_DEFINITION_NOT_EXISTS);
//        }
        // 1.2 校验是否能够发起

        // 1.3 校验发起人自选审批人
        // validateStartUserSelectAssignees(definition, startUserSelectAssignees);

        // 2. 创建流程实例
        if (variables == null) {
            variables = new HashMap<>();
        }
        identityService.setAuthenticatedUserId(userId.toString());
        FlowableUtils.filterProcessInstanceFormVariable(variables); // 过滤一下，避免 ProcessInstance 系统级的变量被占用
        variables.put(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_START_USER_ID, userId); // 设置流程变量，发起人 ID
        variables.put(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, // 流程实例状态：审批中
                BpmProcessInstanceStatusEnum.RUNNING.getStatus());
        variables.put(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_BUSINESS_KEY,businessKey);
        variables.put(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_TABLE_NAME,tableName);
        if (CollUtil.isNotEmpty(startUserSelectAssignees)) {
            variables.put(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_START_USER_SELECT_ASSIGNEES, startUserSelectAssignees);
        }
        ProcessInstance instance = runtimeService.createProcessInstanceBuilder()
                .processDefinitionId(definition.getId())
                .businessKey(businessKey)
                .name(definition.getName().trim())
                .variables(variables)
                .start();

        return instance.getId();
    }


    /**
     * 根据流程定义ID启动流程实例
     *
     * @param procDefId 流程定义Id
     * @param variables 流程变量
     * @return
     */
    @Override
    public AjaxResult startProcessInstanceById(String procDefId, Map<String, Object> variables) {

        try {
            // 设置流程发起人Id到流程中
            Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
//            identityService.setAuthenticatedUserId(userId.toString());
            variables.put("initiator",userId);
            variables.put("_FLOWABLE_SKIP_EXPRESSION_ENABLED", true);
            runtimeService.startProcessInstanceById(procDefId, variables);
            return AjaxResult.success("流程启动成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("流程启动错误");
        }
    }

    @Override
    public ProcessInstance getProcessInstance(String id) {
        return runtimeService.createProcessInstanceQuery()
                .includeProcessVariables()
                .processInstanceId(id)
                .singleResult();
    }

    @Override
    public void updateProcessInstanceReject(ProcessInstance processInstance, String reason) {
        runtimeService.setVariable(processInstance.getProcessInstanceId(), BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS,
                BpmProcessInstanceStatusEnum.REJECT.getStatus());
        runtimeService.setVariable(processInstance.getProcessInstanceId(), BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_REASON,
                BpmReasonEnum.REJECT_TASK.format(reason));
    }

    //@Override
    public HistoricProcessInstance getHistoricProcessInstance(String id) {
        return historyService.createHistoricProcessInstanceQuery().processInstanceId(id).includeProcessVariables().singleResult();
    }

    @Override
    public BpmApprovalDetailRespVO getApprovalDetail(Long loginUserId, BpmApprovalDetailReqVO reqVO) {
        // 1.1 从 reqVO 中，读取公共变量
        Long startUserId = loginUserId; // 流程发起人
        HistoricProcessInstance historicProcessInstance = null; // 流程实例
        Integer processInstanceStatus = BpmProcessInstanceStatusEnum.NOT_START.getStatus(); // 流程状态
        Map<String, Object> processVariables = reqVO.getProcessVariables(); // 流程变量
        // 1.2 如果是流程已发起的场景，则使用流程实例的数据
        if (reqVO.getProcessInstanceId() != null) {
            historicProcessInstance = getHistoricProcessInstance(reqVO.getProcessInstanceId());
            if (historicProcessInstance == null) {
                throw exception(ErrorCodeConstants.PROCESS_INSTANCE_NOT_EXISTS);
            }
            startUserId = Long.valueOf(historicProcessInstance.getStartUserId());
            processInstanceStatus = FlowableUtils.getProcessInstanceStatus(historicProcessInstance);
            processVariables = historicProcessInstance.getProcessVariables();
        }
        // 1.3 读取其它相关数据
        ProcessDefinition processDefinition = repositoryService.getProcessDefinition(
                historicProcessInstance != null ? historicProcessInstance.getProcessDefinitionId() : reqVO.getProcessDefinitionId());
       // BpmProcessDefinitionInfoDO processDefinitionInfo = processDefinitionService.getProcessDefinitionInfo(processDefinition.getId());
       BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());

        // 2.1 已结束 + 进行中的活动节点
        List<BpmApprovalDetailRespVO.ActivityNode> endActivityNodes = null; // 已结束的审批信息
        List<BpmApprovalDetailRespVO.ActivityNode> runActivityNodes = null; // 进行中的审批信息
        List<HistoricActivityInstance> activities = null; // 流程实例列表
        if (reqVO.getProcessInstanceId() != null) {
            activities = flowTaskService.getActivityListByProcessInstanceId(reqVO.getProcessInstanceId());
            List<HistoricTaskInstance> tasks = flowTaskService.getTaskListByProcessInstanceId(reqVO.getProcessInstanceId(), true);
            endActivityNodes = getEndActivityNodeList(startUserId, bpmnModel,
                    historicProcessInstance, processInstanceStatus, activities, tasks);
            runActivityNodes = getRunApproveNodeList(startUserId, bpmnModel, processDefinition, processVariables, activities, tasks);
        }

        // 2.2 流程已经结束，直接 return，无需预测
        if (BpmProcessInstanceStatusEnum.isProcessEndStatus(processInstanceStatus)) {
            return buildApprovalDetail(reqVO, bpmnModel, processDefinition, historicProcessInstance,
                    processInstanceStatus, endActivityNodes, runActivityNodes, null, null);
        }

        // 3.1 计算当前登录用户的待办任务
        // TODO @jason：有一个极端情况，如果一个用户有 2 个 task A 和 B，A 已经通过，B 需要审核。这个时，通过 A 进来，todo 拿到 B，会不会表单权限不一致哈。
        BpmTaskRespVO todoTask = flowTaskService.getFirstTodoTask(loginUserId, reqVO.getProcessInstanceId());

        // 3.2 预测未运行节点的审批信息
        List<BpmApprovalDetailRespVO.ActivityNode> simulateActivityNodes = getSimulateApproveNodeList(startUserId, bpmnModel, processDefinition,
                processVariables, activities);

        // 4. 拼接最终数据
        return buildApprovalDetail(reqVO, bpmnModel, processDefinition, historicProcessInstance,
                processInstanceStatus, endActivityNodes, runActivityNodes, simulateActivityNodes, todoTask);
    }

    /**
     * 获得【预测（未来）】的活动节点们
     */
    private List<BpmApprovalDetailRespVO.ActivityNode> getSimulateApproveNodeList(Long startUserId, BpmnModel bpmnModel, ProcessDefinition processDefinition,
                                                                                  Map<String, Object> processVariables,
                                                                                  List<HistoricActivityInstance> activities) {
        // TODO @芋艿：【可优化】在驳回场景下，未来的预测准确性不高。原因是，驳回后，HistoricActivityInstance 包括了历史的操作，不是只有 startEvent 到当前节点的记录
        Set<String> runActivityIds = convertSet(activities, HistoricActivityInstance::getActivityId);
        // 情况一：BPMN 设计器
       // if (Objects.equals(BpmModelTypeEnum.BPMN.getType(), processDefinitionInfo.getModelType())) {
            List<FlowElement> flowElements = BpmnModelUtils.simulateProcess(bpmnModel, processVariables);
            return convertList(flowElements, flowElement -> buildNotRunApproveNodeForBpmn(startUserId, bpmnModel,processDefinition,
                     processVariables, flowElement, runActivityIds));
        //}
        // 情况二：SIMPLE 设计器
//        if (Objects.equals(BpmModelTypeEnum.SIMPLE.getType(), processDefinitionInfo.getModelType())) {
//            BpmSimpleModelNodeVO simpleModel = JsonUtils.parseObject(processDefinitionInfo.getSimpleModel(), BpmSimpleModelNodeVO.class);
//            List<BpmSimpleModelNodeVO> simpleNodes = SimpleModelUtils.simulateProcess(simpleModel, processVariables);
//            return convertList(simpleNodes, simpleNode -> buildNotRunApproveNodeForSimple(startUserId, bpmnModel,
//                    processDefinitionInfo, processVariables, simpleNode, runActivityIds));
//        }
       // throw new IllegalArgumentException("未知设计器类型：" + processDefinitionInfo.getModelType());
    }

    private BpmApprovalDetailRespVO.ActivityNode buildNotRunApproveNodeForBpmn(Long startUserId, BpmnModel bpmnModel, ProcessDefinition processDefinition,
                                                                                Map<String, Object> processVariables,
                                                                               FlowElement node, Set<String> runActivityIds) {
        if (runActivityIds.contains(node.getId())) {
            return null;
        }
        BpmApprovalDetailRespVO.ActivityNode activityNode = new BpmApprovalDetailRespVO.ActivityNode();
        activityNode.setId(node.getId());
        activityNode.setStatus(TaskStatusEnum.NOT_START.getStatus());

        // 1. 开始节点
        if (node instanceof StartEvent) {
             activityNode.setName(BpmSimpleModelNodeType.START_USER_NODE.getName());
             activityNode.setNodeType(BpmSimpleModelNodeType.START_USER_NODE.getType());

            return  activityNode;
        }

        // 2. 审批节点
        if (node instanceof UserTask) {
            List<Long> candidateUserIds = getTaskCandidateUserList(bpmnModel, node.getId(),
                    startUserId, processDefinition.getId(), processVariables);
             activityNode.setName(node.getName());
            activityNode.setNodeType(BpmSimpleModelNodeType.APPROVE_NODE.getType());
            activityNode.setCandidateStrategy(BpmnModelUtils.parseCandidateStrategy(node));
            activityNode.setCandidateUserIds(candidateUserIds);
            return activityNode;
        }

        // 3. 结束节点
        if (node instanceof EndEvent) {
             activityNode.setName(BpmSimpleModelNodeType.END_NODE.getName());
            activityNode.setNodeType(BpmSimpleModelNodeType.END_NODE.getType());
            return activityNode;
        }
        return null;
    }
    /**
     * 获得【进行中】的活动节点们
     */
    private List<BpmApprovalDetailRespVO.ActivityNode> getRunApproveNodeList(Long startUserId,
                                                                             BpmnModel bpmnModel,
                                                                             ProcessDefinition processDefinition,
                                                                             Map<String, Object> processVariables,
                                                                             List<HistoricActivityInstance> activities,
                                                                             List<HistoricTaskInstance> tasks) {
        // 构建运行中的任务，基于 activityId 分组
        List<HistoricActivityInstance> runActivities = filterList(activities, activity -> activity.getEndTime() == null
                && (StrUtil.equalsAny(activity.getActivityType(), ELEMENT_TASK_USER)));
        Map<String, List<HistoricActivityInstance>> runningTaskMap = convertMultiMap(runActivities, HistoricActivityInstance::getActivityId);

        // 按照 activityId 分组，构建 ApprovalNodeInfo 节点
        Map<String, HistoricTaskInstance> taskMap = convertMap(tasks, HistoricTaskInstance::getId);
        return convertList(runningTaskMap.entrySet(), entry -> {
            String activityId = entry.getKey();
            List<HistoricActivityInstance> taskActivities = entry.getValue();
            // 构建活动节点
            FlowElement flowNode = BpmnModelUtils.getFlowElementById(bpmnModel, activityId);
            HistoricActivityInstance firstActivity = CollUtil.getFirst(taskActivities); // 取第一个任务，会签/或签的任务，开始时间相同
            BpmApprovalDetailRespVO.ActivityNode activityNode = new BpmApprovalDetailRespVO.ActivityNode();
            activityNode.setId(firstActivity.getActivityId());
            activityNode.setName(firstActivity.getActivityName());
            activityNode.setNodeType(BpmSimpleModelNodeType.APPROVE_NODE.getType());
            activityNode.setStatus(TaskStatusEnum.RUNNING.getStatus());
            activityNode.setCandidateStrategy(BpmnModelUtils.parseCandidateStrategy(flowNode));
            activityNode.setStartTime(DateUtils.of(CollUtil.getFirst(taskActivities).getStartTime()));
            activityNode.setTasks(new ArrayList<>());
            // 处理每个任务的 tasks 属性
            for (HistoricActivityInstance activity : taskActivities) {
                HistoricTaskInstance task = taskMap.get(activity.getTaskId());
                activityNode.getTasks().add(BpmProcessInstanceConvert.INSTANCE.buildApprovalTaskInfo(task));
                // 加签子任务，需要过滤掉已经完成的加签子任务
                List<HistoricTaskInstance> childrenTasks = filterList(
                        flowTaskService.getAllChildrenTaskListByParentTaskId(activity.getTaskId(), tasks),
                        childTask -> childTask.getEndTime() == null);
                if (CollUtil.isNotEmpty(childrenTasks)) {
                    activityNode.getTasks().addAll(convertList(childrenTasks, BpmProcessInstanceConvert.INSTANCE::buildApprovalTaskInfo));
                }
            }
            // 处理每个任务的 candidateUsers 属性：如果是依次审批，需要预测它的后续审批人。因为 Task 是审批完一个，创建一个新的 Task
            if (BpmnModelUtils.isSequentialUserTask(flowNode)) {
                List<Long> candidateUserIds = getTaskCandidateUserList(bpmnModel, flowNode.getId(),
                        startUserId, processDefinition.getId(), processVariables);
                // 截取当前审批人位置后面的候选人，不包含当前审批人
                BpmApprovalDetailRespVO.ActivityNodeTask approvalTaskInfo = CollUtil.getFirst(activityNode.getTasks());
                Assert.notNull(approvalTaskInfo, "任务不能为空");
                int index = CollUtil.indexOf(candidateUserIds, userId -> ObjectUtils.equalsAny(userId, approvalTaskInfo.getOwner(),
                        approvalTaskInfo.getAssignee())); // 委派或者向前加签情况，需要先比较 owner
                activityNode.setCandidateUserIds(CollUtil.sub(candidateUserIds, index + 1, candidateUserIds.size()));
            }
            return activityNode;
        });
    }

    private List<Long> getTaskCandidateUserList(BpmnModel bpmnModel, String activityId,
                                                Long startUserId, String processDefinitionId, Map<String, Object> processVariables) {
        Set<Long> userIds = taskCandidateInvoker.calculateUsersByActivity(bpmnModel, activityId,
                startUserId, processDefinitionId, processVariables);
        return new ArrayList<>(userIds);
    }
    /**
     * 获得【已结束】的活动节点们
     */
    private List<BpmApprovalDetailRespVO.ActivityNode> getEndActivityNodeList(
            Long startUserId, BpmnModel bpmnModel,
            HistoricProcessInstance historicProcessInstance,
            Integer processInstanceStatus,
            List<HistoricActivityInstance> activities,
            List<HistoricTaskInstance> tasks)
    {
        // 遍历 tasks 列表，只处理已结束的 UserTask
        // 为什么不通过 activities 呢？因为，加签场景下，它只存在于 tasks，没有 activities，导致如果遍历 activities 的话，它无法成为一个节点
        List<HistoricTaskInstance> endTasks = filterList(tasks, task -> task.getEndTime() != null);
        List<BpmApprovalDetailRespVO.ActivityNode> approvalNodes = convertList(endTasks, task -> {
            FlowElement flowNode = BpmnModelUtils.getFlowElementById(bpmnModel, task.getTaskDefinitionKey());
            BpmApprovalDetailRespVO.ActivityNode activityNode = new BpmApprovalDetailRespVO.ActivityNode();
            activityNode.setId(task.getTaskDefinitionKey());
            activityNode.setName(task.getName());
            activityNode.setNodeType(START_USER_NODE_ID.equals(task.getTaskDefinitionKey()) ?
                            BpmSimpleModelNodeType.START_USER_NODE.getType() : BpmSimpleModelNodeType.APPROVE_NODE.getType());
            activityNode.setStatus(FlowableUtils.getTaskStatus(task));
            activityNode.setCandidateStrategy(BpmnModelUtils.parseCandidateStrategy(flowNode));
            activityNode.setStartTime(DateUtils.of(task.getCreateTime()));
            activityNode.setEndTime(DateUtils.of(task.getEndTime()));
            activityNode.setTasks(singletonList(buildApprovalTaskInfo(task)));
            // 如果是取消状态，则跳过
            if (TaskStatusEnum.isCancelStatus(activityNode.getStatus())) {
                return null;
            }
            return activityNode;
        });

        // 遍历 activities，只处理已结束的 StartEvent、EndEvent
        List<HistoricActivityInstance> endActivities = filterList(activities, activity -> activity.getEndTime() != null
                && (StrUtil.equalsAny(activity.getActivityType(), ELEMENT_EVENT_START, ELEMENT_EVENT_END)));
        endActivities.forEach(activity -> {
            // StartEvent：只处理 BPMN 的场景。因为，SIMPLE 情况下，已经有 START_USER_NODE 节点
            if (ELEMENT_EVENT_START.equals(activity.getActivityType())){
                BpmApprovalDetailRespVO.ActivityNodeTask startTask = new BpmApprovalDetailRespVO.ActivityNodeTask();
                startTask.setId(START_USER_NODE_ID);
                startTask.setAssignee(startUserId);
                startTask.setStatus(TaskStatusEnum.APPROVE.getStatus());
                BpmApprovalDetailRespVO.ActivityNode startNode = new BpmApprovalDetailRespVO.ActivityNode();
                startNode.setId(startTask.getId());
                startNode.setName(BpmSimpleModelNodeType.START_USER_NODE.getName());
                startNode.setNodeType(BpmSimpleModelNodeType.START_USER_NODE.getType());
                startNode.setStatus(startTask.getStatus());
                startNode.setTasks(ListUtil.of(startTask));
                startNode.setStartTime(DateUtils.of(activity.getStartTime()));
                        startNode.setEndTime(DateUtils.of(activity.getEndTime()));
                approvalNodes.add(0, startNode);
                return;
            }
            // EndEvent
            if (ELEMENT_EVENT_END.equals(activity.getActivityType())) {
                if (BpmProcessInstanceStatusEnum.isRejectStatus(processInstanceStatus)) {
                    // 拒绝情况下，不需要展示 EndEvent 结束节点。原因是：前端已经展示 x 效果，无需重复展示
                    return;
                }
                BpmApprovalDetailRespVO.ActivityNode endNode = new BpmApprovalDetailRespVO.ActivityNode();
                endNode.setId(activity.getId());
                endNode.setName(BpmSimpleModelNodeType.END_NODE.getName());
                endNode.setNodeType(BpmSimpleModelNodeType.END_NODE.getType());
                endNode.setStatus(processInstanceStatus);
                endNode.setStartTime(DateUtils.of(activity.getStartTime()));
                endNode.setEndTime(DateUtils.of(activity.getEndTime()));
                String reason = FlowableUtils.getProcessInstanceReason(historicProcessInstance);
                if (StrUtil.isNotEmpty(reason)) {
                    BpmApprovalDetailRespVO.ActivityNodeTask activityNodeTask = new BpmApprovalDetailRespVO.ActivityNodeTask();
                    activityNodeTask.setId(endNode.getId());
                    activityNodeTask.setStatus(endNode.getStatus());
                    activityNodeTask.setReason(reason);
                    endNode.setTasks(singletonList(activityNodeTask));
                }
                approvalNodes.add(endNode);
            }
        });
        return approvalNodes;
    }
   public BpmApprovalDetailRespVO.ActivityNodeTask buildApprovalTaskInfo(HistoricTaskInstance task) {
        if (task == null) {
            return null;
        }
        BpmApprovalDetailRespVO.ActivityNodeTask activityNodeTask = new BpmApprovalDetailRespVO.ActivityNodeTask();
        activityNodeTask = BeanUtils.toBean(task, BpmApprovalDetailRespVO.ActivityNodeTask.class);
        activityNodeTask.setStatus(FlowableUtils.getTaskStatus(task));
        activityNodeTask.setReason(FlowableUtils.getTaskReason(task));
        return  activityNodeTask;
    }

    @Override
    public PageResult<HistoricProcessInstance> getProcessInstancePage(Long userId,
                                                                      BpmProcessInstancePageReqVO pageReqVO) {
        // 通过 BpmProcessInstanceExtDO 表，先查询到对应的分页
        HistoricProcessInstanceQuery processInstanceQuery = historyService.createHistoricProcessInstanceQuery()
                .includeProcessVariables()
                .orderByProcessInstanceStartTime().desc();
        if (userId != null) { // 【我的流程】菜单时，需要传递该字段
            processInstanceQuery.startedBy(String.valueOf(userId));
        } else if (pageReqVO.getStartUserId() != null) { // 【管理流程】菜单时，才会传递该字段
            processInstanceQuery.startedBy(String.valueOf(pageReqVO.getStartUserId()));
        }
        if (StrUtil.isNotEmpty(pageReqVO.getName())) {
            processInstanceQuery.processInstanceNameLike("%" + pageReqVO.getName() + "%");
        }
        if (StrUtil.isNotEmpty(pageReqVO.getProcessDefinitionKey())) {
            processInstanceQuery.processDefinitionKey(pageReqVO.getProcessDefinitionKey());
        }
        if (StrUtil.isNotEmpty(pageReqVO.getCategory())) {
            processInstanceQuery.processDefinitionCategory(pageReqVO.getCategory());
        }
        if (pageReqVO.getStatus() != null) {
            processInstanceQuery.variableValueEquals(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, pageReqVO.getStatus());
        }
        if (ArrayUtil.isNotEmpty(pageReqVO.getCreateTime())) {
            processInstanceQuery.startedAfter(DateUtils.of(pageReqVO.getCreateTime()[0]));
            processInstanceQuery.startedBefore(DateUtils.of(pageReqVO.getCreateTime()[1]));
        }
        // 查询数量
        long processInstanceCount = processInstanceQuery.count();
        if (processInstanceCount == 0) {
            return PageResult.empty(processInstanceCount);
        }
        // 查询列表
        List<HistoricProcessInstance> processInstanceList = processInstanceQuery.listPage
                ((pageReqVO.getPageNo() - 1) * pageReqVO.getPageSize(), pageReqVO.getPageSize());
        return new PageResult<>(processInstanceList, processInstanceCount);
    }



    /**
     * 拼接审批详情的最终数据
     * <p>
     * 主要是，拼接审批人的用户信息、部门信息
     */
    private BpmApprovalDetailRespVO buildApprovalDetail(BpmApprovalDetailReqVO reqVO,
                                                        BpmnModel bpmnModel,
                                                        ProcessDefinition processDefinition,

                                                        HistoricProcessInstance processInstance,
                                                        Integer processInstanceStatus,
                                                        List<BpmApprovalDetailRespVO.ActivityNode> endApprovalNodeInfos,
                                                        List<BpmApprovalDetailRespVO.ActivityNode> runningApprovalNodeInfos,
                                                        List<BpmApprovalDetailRespVO.ActivityNode> simulateApprovalNodeInfos,
                                                        BpmTaskRespVO todoTask) {
        // 1. 获取所有需要读取用户信息的 userIds
        List<BpmApprovalDetailRespVO.ActivityNode> approveNodes = newArrayList(asList(endApprovalNodeInfos, runningApprovalNodeInfos, simulateApprovalNodeInfos));
        Set<Long> userIds = BpmProcessInstanceConvert.INSTANCE.parseUserIds(processInstance, approveNodes, todoTask);
        Map<Long, SysUser> userMap = userService.getUserMap(userIds);
        Map<Long, DeptRespDTO> deptMap=null;

       // Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(convertSet(userMap.values(), AdminUserRespDTO::getDeptId));


        // 2. 表单权限
//        String taskId = reqVO.getTaskId() == null && todoTask != null ? todoTask.getId() : reqVO.getTaskId();
//        Map<String, String> formFieldsPermission = getFormFieldsPermission(bpmnModel, reqVO.getActivityId(), taskId);

        // 3. 拼接数据
        return BpmProcessInstanceConvert.INSTANCE.buildApprovalDetail
                (bpmnModel, processDefinition, processInstance,
                processInstanceStatus, approveNodes, todoTask, userMap, deptMap);
    }

    // ========== Event 事件相关方法 ==========
    @Override
    public void processProcessInstanceCompleted(ProcessInstance instance) {
        // 注意：需要基于 instance 设置租户编号，避免 Flowable 内部异步时，丢失租户编号
        FlowableUtils.execute(instance.getTenantId(), () -> {
            // 1.1 获取当前状态
            Integer status = (Integer) instance.getProcessVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS);
            String reason = (String) instance.getProcessVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_REASON);
            String tablename=(String) instance.getProcessVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_TABLE_NAME);
            String  businessKey=instance.getBusinessKey();

            // 1.2 当流程状态还是审批状态中，说明审批通过了，则变更下它的状态
            // 为什么这么处理？因为流程完成，并且完成了，说明审批通过了
            if (Objects.equals(status, BpmProcessInstanceStatusEnum.RUNNING.getStatus())) {
                status = BpmProcessInstanceStatusEnum.APPROVE.getStatus();
                runtimeService.setVariable(instance.getId(), BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS, status);
            }
            //  businessStatusService.updateBusinessStatus(tablename,businessKey,status.toString());
           // flowDeployMapper.updateTableStatus(tablename,status,businessKey);
            SysUser sysUser=SecurityUtils.getLoginUser().getUser();

            ProcessConfig processConfig= processConfigService.getProcessByTableName(tablename);

            flowDeployMapper.updateTableStatus(tablename,status,instance.getProcessInstanceId(),businessKey);
            if(processConfig!=null&&processConfig.getCallApi().equals(1))
            {    businessApi.get(tablename).updateBusinessStatus(tablename,businessKey,status.toString(),sysUser.getUserId().toString());}
            // 2. 发送对应的消息通知
            SysUser startUser=userService.selectUserById(Long.parseLong(instance.getStartUserId()));
            if (Objects.equals(status, BpmProcessInstanceStatusEnum.APPROVE.getStatus())) {
                messageService.sendMessageWhenProcessInstanceApprove(BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceApproveMessage(instance,reason,startUser));
            } else if (Objects.equals(status, BpmProcessInstanceStatusEnum.REJECT.getStatus())) {
                messageService.sendMessageWhenProcessInstanceReject(
                        BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceRejectMessage(instance,reason,startUser));
            }

            // 3. 发送流程实例的状态事件
//            processInstanceEventPublisher.sendProcessInstanceResultEvent(
//                    BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceStatusEvent(this, instance, status));
        });
    }

    @Override
    public void processProcessInstanceCreated(ProcessInstance instance) {

    }

    @Override
    public void processProcessInstanceStarted(FlowableProcessStartedEvent event) {
        ProcessInstance instance=  (ProcessInstance)event.getEntity();
        Integer status = (Integer) event.getVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS);
        String tablename=(String) event.getVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_TABLE_NAME);
        String businessKey=(String) event.getVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_BUSINESS_KEY);
        flowDeployMapper.updateTableStatus(tablename,status,instance.getProcessInstanceId(),businessKey);
    }


    @Override
    public BpmProcessInstanceBpmnModelViewRespVO getProcessInstanceBpmnModelView(String id) {
        // 1.1 获得流程实例
        HistoricProcessInstance processInstance = getHistoricProcessInstance(id);
        if (processInstance == null) {
            return null;
        }
        // 1.2 获得流程定义
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        if (bpmnModel == null) {
            return null;
        }



        // 1.3 获得流程实例对应的活动实例列表 + 任务列表
        List<HistoricActivityInstance> activities = flowTaskService.getActivityListByProcessInstanceId(id);
        List<HistoricTaskInstance> tasks = flowTaskService.getTaskListByProcessInstanceId(id, true);

        // 2.1 拼接进度信息
        Set<String> unfinishedTaskActivityIds = convertSet(activities, HistoricActivityInstance::getActivityId,
                activityInstance -> activityInstance.getEndTime() == null);
        Set<String> finishedTaskActivityIds = convertSet(activities, HistoricActivityInstance::getActivityId,
                activityInstance -> activityInstance.getEndTime() != null
                        && ObjectUtil.notEqual(activityInstance.getActivityType(), BpmnXMLConstants.ELEMENT_SEQUENCE_FLOW));
        Set<String> finishedSequenceFlowActivityIds = convertSet(activities, HistoricActivityInstance::getActivityId,
                activityInstance -> activityInstance.getEndTime() != null
                        && ObjectUtil.equals(activityInstance.getActivityType(), BpmnXMLConstants.ELEMENT_SEQUENCE_FLOW));
        // 特殊：会签情况下，会有部分已完成（审批）、部分未完成（待审批），此时需要 finishedTaskActivityIds 移除掉
        finishedTaskActivityIds.removeAll(unfinishedTaskActivityIds);
        // 特殊：如果流程实例被拒绝，则需要计算是哪个活动节点。
        // 注意，只取最后一个。因为会存在多次拒绝的情况，拒绝驳回到指定节点
        Set<String> rejectTaskActivityIds = CollUtil.newHashSet();
        if (BpmProcessInstanceStatusEnum.isRejectStatus(FlowableUtils.getProcessInstanceStatus(processInstance))) {
            tasks.stream()
                    .filter(task -> TaskStatusEnum.isRejectStatus(FlowableUtils.getTaskStatus(task)))
                    .max(Comparator.comparing(HistoricTaskInstance::getEndTime))
                    .ifPresent(reject -> rejectTaskActivityIds.add(reject.getTaskDefinitionKey()));
            finishedTaskActivityIds.removeAll(rejectTaskActivityIds);
        }

        // 2.2 拼接基础信息
        Set<Long> userIds = BpmProcessInstanceConvert.INSTANCE.parseUserIds02(processInstance, tasks);
        Map<Long, SysUser> userMap = userService.getUserMap(userIds);
       // Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(convertSet(userMap.values(), AdminUserRespDTO::getDeptId));
         Map<Long, DeptRespDTO> deptMap = null;
        return BpmProcessInstanceConvert.INSTANCE.buildProcessInstanceBpmnModelView(processInstance, tasks, bpmnModel,
                unfinishedTaskActivityIds, finishedTaskActivityIds, finishedSequenceFlowActivityIds, rejectTaskActivityIds,
                userMap, deptMap);
    }

    @Override
    public void cancelProcessInstanceByStartUser(Long userId, BpmProcessInstanceCancelReqVO cancelReqVO) {
        // 1.1 校验流程实例存在
        ProcessInstance instance = getProcessInstance(cancelReqVO.getId());
        if (instance == null) {
            throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS);
        }
        // 1.2 只能取消自己的
        if (!Objects.equals(instance.getStartUserId(), String.valueOf(userId))) {
            throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_SELF);
        }

        // 2. 取消流程
        updateProcessInstanceCancel(cancelReqVO.getId(),
                BpmReasonEnum.CANCEL_PROCESS_INSTANCE_BY_START_USER.format(cancelReqVO.getReason()));
    }

    @Override
    public void cancelProcessInstanceByStartUserForce(Long userId, BpmProcessInstanceCancelReqVO cancelReqVO) {
        ProcessInstance instance = getProcessInstance(cancelReqVO.getId());

        if (instance == null) {
            throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS);
        }
        // 1.2 只能取消自己的
        if (!Objects.equals(instance.getStartUserId(), String.valueOf(userId))) {
            throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_SELF);
        }
        String instanceId=cancelReqVO.getId();
        Integer status = 4;
        String tablename=(String) instance.getProcessVariables().get(BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_TABLE_NAME);
        String  businessKey=instance.getBusinessKey();
        flowDeployMapper.updateTableStatus(tablename,status,instanceId,businessKey);
        HistoricProcessInstance historicProcessInstance = getHistoricProcessInstanceById(instanceId);
        if (historicProcessInstance.getEndTime() != null) {
            historyService.deleteHistoricProcessInstance(historicProcessInstance.getId());
            return;
        }
        runtimeService.deleteProcessInstance(cancelReqVO.getId(),"");
        // 删除流程实例
        // 删除历史流程实例
        historyService.deleteHistoricProcessInstance(instanceId);

    }

    @Override
    public void cancelProcessInstanceByAdmin(Long userId, BpmProcessInstanceCancelReqVO cancelReqVO) {
        // 1.1 校验流程实例存在
        ProcessInstance instance = getProcessInstance(cancelReqVO.getId());
        if (instance == null) {
            throw exception(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS);
        }

        // 2. 取消流程
        SysUser user = userService.selectUserById(userId);
        updateProcessInstanceCancel(cancelReqVO.getId(),
                BpmReasonEnum.CANCEL_PROCESS_INSTANCE_BY_ADMIN.format(user.getUserName(), cancelReqVO.getReason()));
        runtimeService.setVariable(cancelReqVO.getId(), BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS,
                BpmProcessInstanceStatusEnum.CANCEL.getStatus());
    }
    private void updateProcessInstanceCancel(String id, String reason) {
        // 1. 更新流程实例 status
        runtimeService.setVariable(id, BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_STATUS,
                BpmProcessInstanceStatusEnum.CANCEL.getStatus());
        runtimeService.setVariable(id, BpmnVariableConstants.PROCESS_INSTANCE_VARIABLE_REASON, reason);

        // 2. 结束流程
        flowTaskService.moveTaskToEnd(id);
    }
}